<?php
require_once( dirname(__FILE__).'/../libs/bedmintonlib.php' );

class Court 
{
    public $type; // COURT_TYPE
    public $courtNumber; // 0-4
    public $reserved; // array with 24 elements // RESERVATION_TYPE
    public function __construct( $_typ, $_courtNumber )
    {
        $this->type = $_typ;
        $this->courtNumber = $_courtNumber;
        $this->reserved = array();
        $this->myreserved = array();
        for ($i = 0; $i < 24; $i ++)
        {
            $this->reserved[ $i ] = -1;
            $this->myreserved[ $i ] = -1;
        }
    }
}

function legend()
{
    $reservation = "Rezervácia";
    $fixedTerm = "Pevný termín";
    $holiday = "Údržba/dovolenka";
    $tournament = "Turnaj";
    $myReservations = "Moje rezervácie - ";
    
    if (isEnglish())
    {
        $reservation = "Reservation";
        $fixedTerm = "Fixed term";
        $holiday = "Maintenance/holiday";
        $tournament = "Tournament";
        $myReservations = "My reservations - ";
    }
    echo ( "
        <table class = \"legend\"><tr>
        <td>$reservation</td><td><hr class=\"reservationItemStyleReservation\" /></td>
        <td>$fixedTerm</td><td><hr class=\"reservationItemStyleFixedTerm\" /></td>
        <td>$holiday</td><td><hr class=\"reservationItemStyleFailure\" /></td>
        <td>$tournament</td><td><hr class=\"reservationItemStyleTournament\" /></td>
        <td>$myReservations</td><td><b>M</b></td>
        </tr></table>
        " );
}

function fromTimeToTime( $date, & $fromTime, & $toTime )
{
    $dayType = 0;
    $dw = date( "w", strtotime( $date ) );
    if ($dw == 0 || $dw == 6)
        $dayType = 1;

    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
    {
        echo( $db->getErrorStr() );
        return false;
    }

    try
    {
        $statement = $dbConnection->prepare( "SELECT fromtimenumber, totimenumber FROM openhours WHERE daydate = ?");
        $statement->bindParam( 1, $date, PDO::PARAM_STR );
        $statement->execute();
        $result = $statement->fetch( PDO::FETCH_NUM );
        if (! $result)
        {
            $statement = $dbConnection->prepare( "SELECT fromtimenumber, totimenumber FROM openhours WHERE daytype = ? AND daydate IS NULL");
            $statement->bindParam( 1, $dayType, PDO::PARAM_INT );
            $statement->execute();
            $result = $statement->fetch( PDO::FETCH_NUM );
            if (! $result)
            {
                logError( __FUNCTION__ . ": Unable to fetch from openhours" );
                return false;
            }
        }
        
        $fromTime = $result[0];
        $toTime = $result[1];
    }
    catch(PDOException $e)
    {
        logError(  __FUNCTION__ . ": " . $e->getMessage() );
        return false;
    }
    
    return true;
}

function readCourtsReservations( $date, & $courts )
{
    $courts = array();
    $courts[ 0 ] = new Court( 0, 0 );
    $courts[ 1 ] = new Court( 0, 1 );
    $courts[ 2 ] = new Court( 0, 2 );
    $courts[ 3 ] = new Court( 1, 3 );
    $courts[ 4 ] = new Court( 1, 4 );

    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
    {
        echo( $db->getErrorStr() );
        return false;
    }

    try
    {
        $loggedUser = null;
        if (isset( $_SESSION[ 'logged_user' ] ))
            $loggedUser = unserialize( $_SESSION[ 'logged_user' ] );

        $statement = $dbConnection->prepare( "SELECT customerid, courtnumber, timenumber, reservationtype FROM reservations WHERE reservationdate = ?");
        $statement->bindParam( 1, $date, PDO::PARAM_STR );
        $statement->execute();
        $result = $statement->fetchAll( PDO::FETCH_NUM );
        if (! $result)
            return true;
        
        foreach($result as $row)
        {
            $customerId = $row[0];
            $courtNumber = $row[1];
            $timeNumber = $row[2];
            $reservationtype = $row[3];
            
            $courts[ $courtNumber ]->courtNumber = $courtNumber;
            $courts[ $courtNumber ]->type = $courtNumber < 3 ? 0 : 1;
            $courts[ $courtNumber ]->reserved[ $timeNumber ] = $reservationtype;
            if (isset( $loggedUser ) && $loggedUser->id == $customerId)
            {
                $courts[ $courtNumber ]->myreserved[ $timeNumber ] = $reservationtype;
            }
        }
    }
    catch(PDOException $e)
    {
        logError(  __FUNCTION__ . ": " . $e->getMessage() );
        return false;
    }
   
    return true;
}

function printReservationItem( $reservationType, $myReservationType, $courtnumber, $index, $enableReservation )
{
    global $enum;
    $id = sprintf("\"td%d_%d\"", $courtnumber, $index );

    $tdTextClass = "";
    $tdText = "&nbsp";
    if ($myReservationType != $enum['RESERVATION_TYPE_FREE'] && $reservationType == $myReservationType)
    {
        $tdText = "M";
        $tdTextClass = "reservationItemText";
    }
    
    $tdStr = "";
    switch ($reservationType)
    {
    case $enum['RESERVATION_TYPE_FREE']:
        $tdStr = $enableReservation ? "<td id = $id class = \"reservationItemStyle\"></td>" : "<td>$tdText</td>";
        break;
    
    case $enum['RESERVATION_TYPE_RESERVATION']:
        $tdStr = "<td id = $id class = \"reservationItemStyleReservation $tdTextClass\">$tdText</td>";
        break;
    
    case $enum['RESERVATION_TYPE_FIXED_TERM']:
        $tdStr = "<td id = $id class = \"reservationItemStyleFixedTerm $tdTextClass\">$tdText</td>";
        break;
    case $enum['RESERVATION_TYPE_HOLIDAY']:
    case $enum['RESERVATION_TYPE_FAILURE']:
        $tdStr = "<td class = \"reservationItemStyleFailure $tdTextClass\">$tdText</td>";
        break;
    case $enum['RESERVATION_TYPE_TOURNAMENT']:
        $tdStr = "<td class = \"reservationItemStyleTournament $tdTextClass\">$tdText</td>";
        break;

    default:
        break;
    
    }

    return $tdStr;
}

function printTableForCourt( $courtType, $fromTime, $toTime, & $courtReservations, $currentDay )
{
    global $enum;
    $tableStr = "<table class=\"reservationtable\"><thead><tr><th>" . ( isEnglish() ? "Court" : "Kurt" ) . "</th>";
    for ($i = $fromTime; $i <= $toTime; $i ++)
    {
        $thStr = $i < 10 ? sprintf( "&nbsp;%d", $i ) : $i;
        $courtType == $enum['COURT_TYPE_A'] ? $thStr .= ":00" : $thStr .= ":30";
        $tableStr .= "<th>" . $thStr . "</th>";
    }
    $tableStr .= "</tr></thead>";
    $enableReservation = isset( $_SESSION[ 'logged_user' ] );
    
    $now = getdate();
    $curHour = $now['hours'];
    foreach($courtReservations as $court)
    {
        if ($court->type == $courtType)
        {
            $tableStr .= "<tr><td class=\"courtNumberCell\">" . ( $court->courtNumber + 1 ) . "</td>";
            // cislo kurtu
            for ($i = $fromTime; $i <= $toTime; $i ++)
            {
                $enableReserve = $enableReservation;
                if ($currentDay && $i < $curHour )
                {
                     $enableReserve = false;
                }
                $tableStr .= printReservationItem( $court->reserved[ $i ], $court->myreserved[ $i ], $court->courtNumber, $i, $enableReserve );
            }
            
            $tableStr .= "</tr>";
        }
    }
    $tableStr .= "</table><p>";
    echo( $tableStr );
 }
  
    if (! isset( $_GET[ 'reservationDate' ] ))
    {
        echo( "Reservation date not defined" );
        exit;
    }
    
    //$reservationDate = date( DATE_ISO8601 );
    $reservationDate = $_GET[ 'reservationDate' ];
      
    // pojde to do databazy
    $fromTime = 0;
    $toTime = 23;
    if (! fromTimeToTime( $reservationDate, $fromTime, $toTime ))
        exit;
    
    if (! readCourtsReservations( $reservationDate, $courtReservations ))
        exit;
    
    $currentDay = false;
    $myDateTime = MyDateTime::fromPqDate( $reservationDate );
    $now = getdate();
    if ($myDateTime->day == $now['mday'] && $myDateTime->month == $now['mon'])
        $currentDay = true;
    
    printTableForCourt( $enum['COURT_TYPE_A'], $fromTime, $toTime, $courtReservations, $currentDay );
    printTableForCourt( $enum['COURT_TYPE_B'], $fromTime, $toTime, $courtReservations, $currentDay );

    $javascriptStr = "
    <script type=\"text/javascript\">
    
    $(\".reservationItemStyle\").click(function()
    {
        addOrRemoveReservation( $(this).attr( 'id' ), 1 );  
    });
    
    $(\".reservationItemText\").click(function()
    {
        addOrRemoveReservation( $(this).attr( 'id' ), 0 ); 
    });

    function addOrRemoveReservation( id, confirmReservation )
    {    
        var courtnumber = id.substring( 2, 3 );
        var timenumber = id.substring( 4 );
        var urlStr= '../ajax/confirmdenyreservation.php?reservationDate=$reservationDate&courtNumber=' + courtnumber + '&timeNumber=' + timenumber + '&confirmReservation=' + confirmReservation;
        $(\"#reservationConfirm\").load( urlStr );
    }

    </script>";

    echo( $javascriptStr );
    echo( "<div id=\"reservationConfirm\"></div>" );
    legend();

    /*
//$.getJSON(urlStr, function(output)
            //{
            //    if (output.returnValue == 'true')
            //    {
            //        var idStr = '#' + id;
            //        $(idStr).addClass('reservationItemStyleReservation').removeClass('reservationItemStyle');
            //        $(this).removeAttr(id);
            //    }
            //    else
            //    {
            //        alert( output.errorStr );
            //    }
            //});
            */
?>

